#pragma once

#include <iostream>
#include <memory>
#include <string>
#include <cstring>
#include <cstdlib>
#include <signal.h>
#include <pthread.h>
#include <functional>
#include "Logger.hpp"
#include "Comm.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

static const int gdefaultsockfd = -1;
static const int gport = 8080;
static const int gbacklog = 8;

using task_t = std::function<void()>;

class EchoTcpSever
{
private:
    void HardlerIO(int sockfd, InetAddr clint)
    {
        char buffer[1024];
        while(true)
        {
            buffer[0] = 0;
            ssize_t n = read(sockfd, &buffer, sizeof(buffer) - 1);
            if(n > 0)
            {
                //success
                buffer[n] = 0;
                std::string echo_string = "sever echo# ";
                echo_string += buffer;
                LOG(LogLevel::INFO) << clint.ToString() << " say# " << buffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if(n == 0)
            {
                LOG(LogLevel::INFO) << "clint quit" << " sockfd :" << sockfd;
                break;
            }
            else
            {
                LOG(LogLevel::FATAL) << "read clint error" << " sockfd :" << sockfd;
                break;
            }
        }
    }
public:
    EchoTcpSever(uint16_t port = gport)
        : _listen_socket(gdefaultsockfd),
          _port(port)
    {
    }
    // 初始化
    void Init()
    {
        // 1. socket创建套接字
        _listen_socket = socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_socket < 0)
        {
            LOG(LogLevel::ERROR) << "create socket error!";
            exit(SOCKET_CREATE_ERR);
        }
        LOG(LogLevel::INFO) << "create socket success!";

        // 2. bind连接
        InetAddr local(_port);
        if (bind(_listen_socket, local.Addr(), local.Length()) != 0)
        {
            LOG(LogLevel::ERROR) << "bind socket error!";
            exit(SOCKET_BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind socket success!";

        // 3. listen 监听连接
        if (listen(_listen_socket, gbacklog) != 0)
        {
            LOG(LogLevel::ERROR) << "listen socket error!";
            exit(SOCKET_LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen socket success!";
    }
    class ThreadDate
    {
    public:
        ThreadDate(int sockfd, EchoTcpSever* self, InetAddr addr)
            :_sockfd(sockfd),
             _self(self),
             _addr(addr)
        {

        }
    public:
        int _sockfd;
        EchoTcpSever* _self;
        InetAddr _addr;
    };

    static void* Route(void* arg)
    {
        //将arg void*类型强转成ThreadDate类型
        ThreadDate* tp = static_cast<ThreadDate*>(arg);
        //线程分离
        pthread_detach(pthread_self());
        //执行任务
        tp->_self->HardlerIO(tp->_sockfd, tp->_addr);
        delete(tp);

        return nullptr;
    }
    // 启动
    void Start()
    {
        //signal(SIGCHLD, SIG_IGN);
        while (true)
        {
            // 4. accept 接受连接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listen_socket, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error!";
            }
            InetAddr clientaddr(peer);
            LOG(LogLevel::INFO) << "get sockfd accept success, sockfd is : " << sockfd
                                << " client addr: " << clientaddr.ToString();

            //1. 单进程执行
            //HardlerIO(sockfd, clientaddr);

            //2. 多进程执行，加入signal用来屏蔽SOGCHLD信号
            // pid_t id = fork();
            // if(id < 0)
            // {
            //     LOG(LogLevel::FATAL) << "Insufficient resources";
            //     exit(FORK_ERR);
            // }
            // else if(id == 0)
            // {
            //     //child
            //     //子进程不需要_listen_socket，直接关闭，这是一种防御性编程
            //     close(_listen_socket);
            //     HardlerIO(sockfd, clientaddr);
            //     exit(OK);
            // }
            // //父进程直接退出，此后子进程变成孤儿进程，由1号进程统一回收
            // //父进程不需要sockfd了，直接关闭，不然会使得资源泄漏
            // close(sockfd);

            //3. 多线程执行
            // pthread_t t;
            // ThreadDate *tp = new ThreadDate(sockfd, this, clientaddr);
            // //创建线程
            // pthread_create(&t, nullptr, Route, (void*)tp);

            //4. 线程池执行
            //(以上三种做法在面对很多客户端访问的时候会出现承担不了的情况，只适用于做demo代码)
            ThreadPool<task_t>::GetInstance()->Enqueue([sockfd, this, clientaddr](){
                this->HardlerIO(sockfd, clientaddr);
            });
        }
    }
    ~EchoTcpSever()
    {
    }

private:
    int _listen_socket;
    uint16_t _port;
};